import 'package:flutter/material.dart';
import 'package:flutter_architecture_samples_inherited_widget/state_container.dart';
import 'package:flutter_architecture_samples_inherited_widget/widgets/todo_item.dart';
import 'package:todos_app_core/todos_app_core.dart';

import '../models.dart';
import '../screens/detail_screen.dart';

class TodoList extends StatelessWidget {
  const TodoList({super.key});

  Widget get _buildLoading => const Center(
      child: CircularProgressIndicator(key: ArchSampleKeys.todosLoading));

  void _removeTodo(BuildContext context, Todo todo) {
    StateContainer.of(context).removeTodo(todo);
    _showUndoSnackbar(context, todo);
  }

  void _showUndoSnackbar(BuildContext context, Todo todo) {
    final snackBar = SnackBar(
      key: ArchSampleKeys.snackbar,
      duration: Duration(seconds: 2),
      content: Text(
        ArchSampleLocalizations.of(context)!.todoDeleted(todo.task),
        maxLines: 1,
        overflow: TextOverflow.ellipsis,
      ),
      action: SnackBarAction(
        key: ArchSampleKeys.snackbarAction(todo.id),
        label: ArchSampleLocalizations.of(context)!.undo,
        onPressed: () {
          StateContainer.of(context).addTodo(todo);
        },
      ),
    );

    ScaffoldMessenger.of(context).showSnackBar(snackBar);
  }

  ListView _buildList(StateContainerState container) {
    final todos = container.state!.filterTodos;
    // final todos = container.state!.getFilterTodos();
    return ListView.builder(
      itemBuilder: (context, index) {
        final todo = todos[index];
        return TodoItem(
            todo: todo,
            onTap: () {
              Navigator.of(context)
                  .push(MaterialPageRoute(
                      builder: (context) => DetailsScreen(todo: todo)))
                  .then((todo) {
                if (todo is Todo) {
                  _showUndoSnackbar(context, todo);
                }
              });
            },
            onDismissed: (direction) {
              _removeTodo(context, todo);
            },
            onCheckboxChanged: (complete) {
              container.updateTodo(todo, complete: !todo.complete);
            });
      },
      itemCount: todos.length,
    );
  }

  @override
  Widget build(BuildContext context) {
    final container = StateContainer.of(context);
    return container.state!.isLoading ? _buildLoading : _buildList(container);
  }
}
